<?php


namespace app\develop\controller;

// 系统安装
use think\App;
use think\facade\Db;
use think\Model;

class Install extends Base
{
    public function __construct(App $app = null)
    {
        parent::__construct($app);

        if($this->system['install'] && request()->isAjax()) {
            json_response(0, '您已安装，请勿重复安装');
        }

        if($this->system['install'] && !request()->isAjax()) {
            return redirect('Index/index');
        }
    }

    /**
     * 第一步：生成Env配置文件和权限控制数据表
     * @date 2020/8/6 16:02
     */
    public function step1() {
        if(request()->isPost()) {
            try {

                // 创建env文件
                $env_path = dirname(app()->getBasePath()).'\.env';
                file_put_contents($env_path, '');
                $this->write_env($env_path, ['SYSTEM'=>'develop']);
                $this->write_env($env_path, ['resource_url'=>$this->resource_url]);
                $this->write_env($env_path, ['APP_DEBUG'=>'true']);
                $this->write_env($env_path, ['TOKEN_KEY'=>date('Y').date('m').date('d').date('His').time().rand(11111,99999)]);
                $this->write_env($env_path, ['TOKEN_ISS'=>'Admin'.rand(11111,99999)]);
                if(!empty($_POST['oss_open'])){
                    $upload_type = 'oss';
                }elseif(!empty($_POST['cos_open'])){
                    $upload_type = 'cos';
                }elseif(!empty($_POST['aws_open'])){
                    $upload_type = 'aws';
                }elseif(!empty($_POST['qiniu_open'])){
                    $upload_type = 'qiniu';
                }else{
                    $upload_type = 'local';
                }
                $this->write_env($env_path, ['upload_type'=>$upload_type]);
                // 写入OSS配置
                if(!empty($_POST['oss_open'])) {
                    $this->write_env($env_path, [
                        'oss_bucket'        => 'pilihuo',
                        'oss_key_id'        => 'LTAI5tPE7WniQCzNMotP9DEG',
                        'oss_key_secret'    => 'IBO7rKKWMBwJkDaCm9UWQgvAf3wkp2',
                        'oss_upload_url'    => 'http://oss-cn-hangzhou.aliyuncs.com',
                        'oss_static_url'    => 'https://game.vrupup.com/resources/',
                        'oss_static_path'   =>  param_check('oss_dir'),
                        'oss_storage_region'=> 'oss-cn-hangzhou'
                    ]);
                }
                // 写入COS配置
                if(!empty($_POST['cos_open'])) {
                    $this->write_env($env_path, [
                        'cos_bucket'        => 'img-hpjy-1252554569',
                        'cos_secret_id'     => 'AKIDjGwNcdh5RcbMqJkIMBuUrwE3FCuPmQ0O',
                        'cos_secret_key'    => 'PmwchaHkxuZxteohI4yEEwnqBFmjtKUR',
                        'cos_region'        => 'ap-beijing',
                        'cos_static_url'    => 'https://hpjyimg.vrupup.com',
                        'cos_static_path'   => param_check('cos_dir')
                    ]);
                }

                 // 写入AWS配置
                 if(!empty($_POST['aws_open'])) {
                    $this->write_env($env_path, [
                        'aws_bucket'        => 'prd-bd-growrice',
                        'aws_key_id'        => 'AKIAXTYW5IFALNLI3Z6O',
                        'aws_key_secret'    => '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',
                        'aws_region'        => 'cn-northwest-1',
                        'aws_static_path'   => param_check('aws_dir')
                    ]);
                }

                // 写入七牛配置
                if(!empty($_POST['qiniu_open'])) {
                $this->write_env($env_path, [
                    'qiniu_bucket'      => 'pilihuo',
                    'qiniu_key_id'      => 'qYiwSuQ1Z-_LnzF4sQN7rw-wElnl3qMy_g0s0wSy',
                    'qiniu_key_secret'  => '6KymgN9rhjhoEcKR8StFfL-5l7Ji-2RNsGwOHEV7',
                    'qiniu_static_url'  => 'http://r4o39bpfl.hn-bkt.clouddn.com/',
                ]);
            }
                // 写入正式环境配置
                $this->write_env($env_path, ['product'=>[
                    'db_host'       => 'rm-bp1p153yeb567lpo0.mysql.rds.aliyuncs.com',
                    'db_port'       => '3306',
                    'db_char'       => 'utf8mb4',
                    'db_name'       => '',
                    'db_user'       => '',
                    'db_pass'       => '',
                    'db_pre'        => $_POST['develop']['db_pre'],
                    'redis_host'    => 'r-bp18vmtk1409q08i00.redis.rds.aliyuncs.com',
                    'redis_port'    => '6379',
                    'redis_pass'    => '1yVXE0uOItLIBCE',
                    'redis_index'   => $_POST['develop']['redis_index']
                ]]);
                // 写入开发环境配置
                $this->write_env($env_path, ['develop'=>$_POST['develop']]);

                // 写入本地环境配置
                $this->write_env($env_path, ['local'=>[
                    'db_host'       => '127.0.0.1',
                    'db_port'       => '3306',
                    'db_char'       => 'utf8mb4',
                    'db_name'       => $_POST['develop']['db_name'],
                    'db_user'       => $_POST['develop']['db_user'],
                    'db_pass'       => $_POST['develop']['db_pass'],
                    'db_pre'        => $_POST['develop']['db_pre'],
                    'redis_host'    => '127.0.0.1',
                    'redis_port'    => '6379',
                    'redis_pass'    => '',
                    'redis_index'   => 1,
                    'static_url'    =>  '',
                    'static_path'   => param_check('local_dir')
                ]]);
                // 创建数据库
                $pdo = new \PDO("mysql:host={$_POST['develop']['db_host']};", $_POST['develop']['db_user'], $_POST['develop']['db_pass']);
                $pdo->exec("CREATE DATABASE IF NOT EXISTS `{$_POST['develop']['db_name']}`;");
                $pdo = null;
                json_response(1, '写入成功');
            } catch (\Exception $e) {
                json_response(0, '接口错误', [
                    'info' => $e->getMessage(),
                    'line' => $e->getLine()
                ]);
            }
        }else {
            return $this->fetch();
        }
    }

    /**
     * 创建后台代码以及生成sql
     * @date 2020/8/6 16:37
     */
    public function step2() {
        if(request()->isPost()) {
            $app_path  = app()->getBasePath();
            $mg_module = $_POST['mg_module'];
            // 安装模块
            $this->install('mg', $mg_module);
            // 安装锁
            file_put_contents("{$app_path}develop/install.lock", date('Y-m-d H:i:s'));
            file_put_contents("{$app_path}develop/mg_module", json_encode([$_POST['mg_module']]));
            json_response(1, '安装成功');
        }else {
            return $this->fetch();
        }
    }


    /**
     * 写入env文件
     * @param $env_path
     * @param $config
     * @date 2020/8/6 16:37
     */
    private function write_env($env_path, $config) {
        foreach($config as $key=>$value) {
            if(is_array($value)) {
                file_put_contents($env_path, "[{$key}]\n", FILE_APPEND);
                foreach($value as $k=>$v) {
                    file_put_contents($env_path, "{$k}='{$v}'\n", FILE_APPEND);
                }
            }else {
                file_put_contents($env_path, "{$key}='{$value}'\n", FILE_APPEND);
            }
        }
        file_put_contents($env_path, "\n", FILE_APPEND);
    }
}